/*
main.cpp

xssbuster - a XSS exploit filter
Copyright (C) 2006 Jeffrey Davis

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

*/

#include "main.h"
#include <stdlib.h>

void clean_terminate();

int main (int argc, char const* argv[])
{
	XssBuster buster;
	CommandLineProcessor cmdline;
	char *buffer;
	std::string inString;
	
	// If an error occurs, cleanly terminate without leaving any residue
	std::set_terminate(clean_terminate);
	
	// Define default command line options
	cmdline.ModifyOption("-l", "64000");
	// Then parse in the command line
	cmdline.Parse(argc, argv);
	
	// Check if the help option has been declared
	if(cmdline.RetrieveOption("-h") != "")
	{
		// Display the standard help message and exit.
		std::cout << "Usage: " << argv[0] << " [options] [< inputstream]" << std::endl;
		std::cout << std::endl;
		std::cout << "Options:" << std::endl;
		std::cout << "  -h          - View this help" << std::endl;
		std::cout << "  -l [value]  - Set maximum inputstream size in bytes [64000]" << std::endl;
		std::cout << std::endl;
		std::cout << "All other options and values are ignored." << std::endl;
		exit(1);
	}
	
	// Initiate the buffer based off the command line option
	int buffersize = atoi(cmdline.RetrieveOption("-l").c_str());
	if(buffersize < 1) buffersize = 64000;
	buffer = (char *)malloc(buffersize);
	
	// Read the XML stream from the standard input
	std::cin.read(buffer, buffersize);
	std::cin.sync();
	
	// Assign the buffer to a string
	inString.assign(buffer);
	
	// Check the XML source for HTML XSS exploits
	std::string outString;
	try
	{
		outString = buster.Bust(inString);
	}
	catch (std::exception e)
	{
		outString = "";
	}
	
	// Send the reconstructed XML source back to the standard output
	std::cout << outString;
	
	// Free the buffer
	free(buffer);
	
	// Exit with code 1 if the reconstructed XML source was empty, else return code 0
	if(outString == "")
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

void clean_terminate()
{
	exit(1);
}